/*
 * Valentine Gladstein
 * SOLAR ID 108731583
 * Homework #5
 * CSE214
 * Recitation 03-Phil Ammirato
 * Grading TA: Yanjie Li
 */

import java.io.*;
import java.util.*;

public class TreeDriver {
    //The TreeDriver class provides a console-driven menu system for manipulating a Tree object

    public Tree tree; //A reference to the Tree object which the driver will be manipulating
    private int readFromLine;

    /**      
     * Displays the main menu in the standard output and
     * gets the user's input selection.
     * @return The user's entry, converted to lowercase.
     */
    private String displayMenu(){
    
        System.out.println("\n\n-------------------------------");
        System.out.println("Main Menu");
        System.out.println("-------------------------------");
        System.out.println("L: Load input file and build a tree");
        System.out.println("H: Start help session");
        System.out.println("T: Traverse the tree(pre-order)"); 
        System.out.println("B: Move back a step"); 
        System.out.println("Q: Quit the pogram"); 
        System.out.println("-------------------------------\n");
        System.out.println("");
        System.out.print("Please make a selection: ");

        return getInput().toLowerCase();

    }

    /**
     * A helper method used internally to read user input from the standard input
     * @return a string containing the user's input
     */
    private String getInput() {
        String s = "";
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(isr);
        try {
            s = br.readLine();

        } catch (IOException e) {}
        return s;
    }

    /**
     * Provides a way for the user to quit the program gracefully
     *
     */
    private void quit() {
        System.out.println("\nTerminating program normally....\n\n");
        System.exit(0);
    }

    private String getValidLine(BufferedReader reader) {
	try {
	    String temp = reader.readLine();
	    if (temp == null)
		return null;
	    while (temp.equals(""))
		temp = reader.readLine();
	    return temp;
	}
	catch(IOException E) {
	    System.out.println("IOExcpetion occurred while reading file. Remainder of file will not be read.");
	    return null;
	}
    }

    private boolean loadFile() {
	String fileName;
    	BufferedReader reader;

	String label;
	String prompt;
	String message;
    
	TreeNode activeParentNode = null;

 	System.out.print("Please enter the file name: ");
    	fileName = getInput();
    	if (!fileName.endsWith(".txt")){
    	    System.out.println("Selected file is not a text file. Please enter a valid text file.\n\nPress enter to continue.");
    	    getInput();
    	    return false;
    	} 

	try {
    	    reader = new BufferedReader(new FileReader(fileName));
    
	    if (tree == null) {
		if ((label = getValidLine(reader)) == null || !label.equals("root"))
		    return false;
		if ((prompt = getValidLine(reader)) == null)
		    return false;
		if ((message = getValidLine(reader)) == null)
		    return false;
		tree = new Tree(new TreeNode(label, prompt, message));
		activeParentNode = tree.getNodeReference("root");
	    }
   
	    while (true) {
		label = getValidLine(reader);
		if (label == null) 
		    break;
		if (tree.getNodeReference(label.split(" ")[0]) == null) {           //if this node has not yet been defined
		    prompt = getValidLine(reader);
		    if (prompt == null) 
			return false;
		    message = getValidLine(reader);
		    if (message == null) 
			return false;
		    activeParentNode.addChild(new TreeNode(label, prompt, message));
		}
		else { //if this node has already been defined
		    activeParentNode = tree.getNodeReference(label.split(" ")[0]);
		}
	}
	reader.close();
    }
   
    catch(IOException e) {
	System.out.println("File input failed. Please check the file and try again.");
	return false;
    }
    return true;
}


    // private String loadFile() {
    // 	String fileName;
    // 	BufferedReader reader;
    // 	String inputFileString;

    // 	System.out.print("Please enter the file name: ");
    // 	fileName = getInput();
    // 	if (!fileName.endsWith(".txt")){
    // 	    System.out.println("Selected file is not a text file. Please enter a valid text file.\n\nPress enter to continue.");
    // 	    getInput();
    // 	    return null;
    // 	} 
    // 	try {
    // 	    reader = new BufferedReader(new FileReader(fileName));
    // 	    String temp;
    // 	    inputFileString = reader.readLine().split(" ")[0];
    // 	    // if (inputFileString != "root") {
    // 	    // 	System.out.println("Found the bug! (see TreeDriver.loadFile(): 83) inputFileString should equal 'root', but it equals: '" + inputFileString + "'");
    // 	    // 	return null;
    // 	    // }
    // 	    while ((temp = reader.readLine()) != null) {
    // 		inputFileString += ("\n"+ temp);
    // 	    }
    // 	    reader.close();
    // 	}
    // 	catch(IOException e) {
    // 	    System.out.println("File input failed. Please check the file and try again.");
    // 	    return null;
    // 	}
    // 	//	System.out.println("TreeDriver.loadFile() is returning at line 95: " + inputFileString);
    // 	return inputFileString;
    // }

    // private TreeNode getNextNode(String[] stringByLine) {
    // 	String parsedLabel;
    // 	String parsedPrompt;
    // 	String parsedMessage;

    // 	TreeNode tempParent;
    // 	TreeNode tempNode;

    // 	try {
    // 	if (tree == null) {                      //initiate the tree by creating the root node
    // 	    System.out.println("starting tee initialization...");
    // 	    while(stringByLine[readFromLine].equals(""))
    // 		readFromLine++;
    // 	    parsedLabel = stringByLine[readFromLine];
    // 	    readFromLine++;
    // 	    while(stringByLine[readFromLine].equals("")) 
    // 		readFromLine++;
    // 	    parsedPrompt = stringByLine[readFromLine];
    // 	    readFromLine++;
    // 	    while(stringByLine[readFromLine].equals("")) 
    // 		readFromLine++;
    // 	    parsedMessage = stringByLine[readFromLine];
    // 	    readFromLine++;
    // 	    System.out.println("initialization complete!");
    // 	    System.out.println(parsedLabel + ","+parsedPrompt+","+parsedMessage+",");
    // 	    try{Thread.sleep(1000);}catch(InterruptedException E){}
    // 	    return new TreeNode(parsedLabel, parsedPrompt, parsedMessage);
    // 	}

    // 	while(stringByLine[readFromLine].equals("")) 
    // 	    readFromLine++;
    // 	readFromLine++;
    // 	parsedLabel = stringByLine[readFromLine].split(" ")[0];
    // 	if (tree.getNodeReference(parsedLabel) != null) { //if the node has already been defined, then the next lines will define its children
    // 	    tempParent = tree.getNodeReference(parsedLabel);
    // 	    int tempNumChildren;
    // 	    try {tempNumChildren = Integer.parseInt(stringByLine[readFromLine].split(" ")[1]);}
    // 	    catch(NumberFormatException E) {System.out.println("Excpetion caught at TreeDriver.getNextNode(String[])");
    // 		return null;}
	  
    // 	    for (int i = 0; i < tempNumChildren; i++) {
    // 		tempParent.addChild(getNextNode(stringByLine));
    // 	    }
    // 	}
    // 	else {
    // 	    tempParent = tree.getNodeReference("root");
    // 	    while(stringByLine[readFromLine].equals("")) 
    // 		readFromLine++;
    // 	    readFromLine++;
    // 	    parsedPrompt = stringByLine[readFromLine];
    // 	    readFromLine++;
    // 	    while(stringByLine[readFromLine].equals("")) 
    // 		readFromLine++;
    // 	    parsedMessage = stringByLine[readFromLine];
    // 	    //readFromLine++;
    // 	    tempNode= new TreeNode(parsedLabel, parsedPrompt, parsedMessage);
    // 	    tempParent.addChild(tempNode);
    // 	    return tempNode;
    // 	}

    // 	}
    // 	catch(ArrayIndexOutOfBoundsException E) {
    // 	    System.out.println("Unexpaectedly reached end of file while parsing. Please check the input file and try again.");
    //    	}
    // 	return null;
    // }
	
    // private Tree parseFileToTree(String inputString) {
    // 	String[] stringByLine;
    // 	//	Tree tree;
    // 	TreeNode tempNode;

    // 	// String parsedLabel;
    // 	// String parsedPrompt;
    // 	// String parsedMessage;

    // 	stringByLine = inputString.split("\n");
    //     // System.out.println(stringByLine.length);
    // 	// for (int i = 0; i < stringByLine.length; i++) {
    // 	//     //	    System.out.println(stringByLine[i]);
    // 	//     System.out.println("~~~~~~~~~~~");
    // 	// }
    // 	readFromLine = 0;
    // 	tree = new Tree(getNextNode(stringByLine));
    // 	if (tree == null)
    // 	    System.out.println("#############################");
    // 	while((tempNode = getNextNode(stringByLine)) != null) {
    // 	    //	    System.out.println("found where the call is coming from! (171)");
    // 	}
    // 	return tree;
    // }


    private void newSession() {
        tree.beginSession();
    }


    private void traverse() {
	tree.preOrder();
    }


    private void backUp() {
	tree.curNode = tree.prevNode;
    }

    /**
     * Provides a menu-driven system for manipulating the
     * Tree class. This method loops back to displaying
     * the menu after every action the user takes.
     *
     */
    public static void main(String[] args) {
	TreeDriver driver  = new TreeDriver();
	while (true){
	    String str = driver.displayMenu();
	    if (str.equals("l")) {
		if (driver.loadFile() == false) {
		    driver.tree = null;
		    System.out.println("An unexpected error occurred while loading the file. PLease check the file and try again.");
		    continue;
		}
	    }
	    else if (str.equals("h"))
	       	driver.newSession();
	    else if (str.equals("t")) {
	       	driver.traverse();
	    }
	    else if (str.equals("b"))
	       	driver.backUp();
	    else if (str.equals("q"))
		driver.quit();
	    else System.out.println("Input not recognized. Please make a valid selection:");
	}

    }
}



